package cn.openea.perpartner.meily.behavioral.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.meily.behavioral.entity.BehavioralData;
import cn.openea.perpartner.meily.behavioral.entity.BehavioralDataVo;
import cn.openea.perpartner.meily.behavioral.mapper.BehavioralDataMapper;
import cn.openea.perpartner.meily.behavioral.service.IBehavioralDataService;
import cn.openea.perpartner.meily.thirdparty.BpmSystemApi;
import cn.openea.perpartner.meily.web.entity.*;
import cn.openea.perpartner.meily.web.service.*;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author rains
 * @since 2023-06-20 10:58
 */
@Service("behavioralDataService")
public class BehavioralDataServiceImpl extends ServiceImpl<BehavioralDataMapper, BehavioralData> implements IBehavioralDataService {

    @Resource
    private IProvideSamplesService provideSamplesService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private BpmSystemApi bpmSystemApi;
    @Resource
    private ITaskHallService taskHallService;
    @Resource
    private ILearningCourseService courseService;

    /**
     * 根据类型获取列表
     * 类型。0动态；1工作；2商品；3创作
     * @param vo
     * @return
     */
    @Override
    public List<?> getListByType(BehavioralDataVo vo) {

        List<?> list = new ArrayList<>();

        if("0".equals(vo.getType())){
            // 0、获取动态
            LambdaQueryWrapper<BehavioralData> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BehavioralData::getStatus, "1");// 状态。0停用；1启用
            // 企业id
            if(StrUtil.isNotBlank(vo.getEnterpriseNo())){
                wrapper.eq(BehavioralData::getEnterpriseNo, vo.getEnterpriseNo());
            }
            // 关键字搜索
            if (StrUtil.isNotBlank(vo.getSearchStr())){
                wrapper.and(wrap-> wrap.like(BehavioralData::getSubject, vo.getSearchStr())
                        .or().like(BehavioralData::getContent, vo.getSearchStr())
                        .or().like(BehavioralData::getLabel, vo.getSearchStr()));
            }
            wrapper.orderByDesc(BehavioralData::getCreateTime);
            list = list(wrapper);

        } else if("1".equals(vo.getType())){
            // 1、获取工作（未处理关键字查询）
            list = taskHallService.getListByEnterpriseNo(vo.getEnterpriseNo());

        } else if("2".equals(vo.getType())){
            // 2、获取商品
            LambdaQueryWrapper<Goods> goodsWrapper = new LambdaQueryWrapper<>();
            goodsWrapper.eq(Goods::getStatus, "已上架");
            // 企业id
            if(StrUtil.isNotBlank(vo.getEnterpriseNo())){
                goodsWrapper.eq(Goods::getEnterpriseNo, vo.getEnterpriseNo());
            }
            // 关键字
            if (StrUtil.isNotBlank(vo.getSearchStr())) {
                goodsWrapper.and(wrap -> wrap.like(Goods::getGoodsNo, vo.getSearchStr())
                        .or().like(Goods::getGoodsName, vo.getSearchStr())
                        .or().like(Goods::getDetail, vo.getSearchStr())
                        .or().like(Goods::getSupplyChain, vo.getSearchStr())
                        .or().like(Goods::getGoodsTag, vo.getSearchStr())
                        .or().like(Goods::getBrand, vo.getSearchStr()));
            }
            // 创建时间降序
            goodsWrapper.orderByDesc(Goods::getCreateTime);
            list = goodsService.list(goodsWrapper);
        } else if("3".equals(vo.getType())){
            // 3、获取创作
            LambdaQueryWrapper<LearningCourse> courseWrapper = new LambdaQueryWrapper<>();
            courseWrapper.eq(LearningCourse::getStatus, "1");// 状态。0:未上架；1:已上架
            // 企业id
            if(StrUtil.isNotBlank(vo.getEnterpriseNo())){
                courseWrapper.eq(LearningCourse::getEnterpriseNo, vo.getEnterpriseNo());
            }
            // 关键字
            if (StringUtils.isNotBlank(vo.getSearchStr())) {
                courseWrapper.and(wrap -> wrap.like(LearningCourse::getTitle, vo.getSearchStr())
                        .or().like(LearningCourse::getEnterpriseName, vo.getSearchStr())
                        .or().like(LearningCourse::getCategory, vo.getSearchStr())
                        .or().like(LearningCourse::getTags, vo.getSearchStr()));
            }
            // 创建时间降序
            courseWrapper.orderByDesc(LearningCourse::getCreateTime);
            list = courseService.list(courseWrapper);
        }

        return list;
    }

    /**
     * 处理历史数据
     * 1.发布样品
     * 2.发布测评
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public boolean dealHistoricalData() {

        /*（1）上架商品
        文案：我刚上架了一款新产品，快来看看吧。
        图片：商品首图；标题：商品标题；小字：商品规格；金额：玫丽价；标签：去掉
        （2）发起品牌推广/样品推广
        文案：我刚发布了一个新活动，快来跟我一起组队吧。
        图片：活动首图；标题：活动标题；小字：商品/样品规格；
        品牌推广：金额+标签“品牌推广报酬”
        样品推广：金额+标签“样品推广价”*/

        // 1.上架商品
        releaseGoods();

        // 1.发布样品
        releaseSamples();

        // 2.发布测评
        releaseEvaluation();

        return true;
    }

    /**
     * 1.上架商品
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void releaseGoods(){

        // 1.获取企业编号不为空的商品列表
        LambdaQueryWrapper<Goods> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(Goods::getEnterpriseNo, "");
        wrapper.isNotNull(Goods::getEnterpriseNo);
        wrapper.orderByDesc(Goods::getCreateTime);

        // 2.遍历
        List<Goods> list = goodsService.list(wrapper);
        for (Goods goods : list) {
            /*上架商品
            文案：我刚上架了一款新产品，快来看看吧。
            图片：商品首图；标题：商品标题；小字：商品规格；金额：玫丽价；标签：去掉*/
            BehavioralData behavioralData = new BehavioralData();
            behavioralData.setTitle("我刚上架了一款新产品，快来看看吧。");// 文案
            behavioralData.setSubject(goods.getGoodsName());// 标题
            behavioralData.setContent(goods.getSpecification());// 内容（商品/样品规格）
            if (StrUtil.isNotBlank(goods.getGoodsImages())) {
                behavioralData.setImage(goods.getGoodsImages().split(",")[0]);// 图片
            }
            behavioralData.setPrice(goods.getDiscountPrice());
            behavioralData.setLabel(goods.getGoodsTag());
            behavioralData.setType("0");// 类型。0动态；1工作；2商品；3创作
            behavioralData.setJumpUrl("/pages_private_scene2/GroupPurchase/DistributionGoods?goodsNo=" + goods.getGoodsNo() + "&goodsId=" + goods.getGoodsId());// 商品详情页面
            behavioralData.setSourceId(String.valueOf(goods.getGoodsId()));// 来源id
            behavioralData.setSourceType("5");// 来源类型。0团购；1测评；2样品；3招聘；4协作；5上架商品；6发布学习
            behavioralData.setUserId(goods.getCreateUser());
            behavioralData.setUserName("");
            behavioralData.setStatus("1");// 状态。0停用；1启用
            behavioralData.setEnterpriseNo(goods.getEnterpriseNo());// 企业编号
            behavioralData.setEnterpriseName(goods.getEnterpriseName());// 企业名称
            behavioralData.setCreateTime(goods.getReleaseTime());
            behavioralData.setUpdateTime(DateUtil.now());
            if(baseMapper.insert(behavioralData) < 0){
                throw new ServiceException("上架商品行为汇集出错了！");
            }
        }
    }

    /**
     * 1.汇集发布样品数据
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void releaseSamples(){

        // 获取已发布的样品活动中，商品的企业编号不为空的数据记录
        MPJLambdaWrapper<ProvideSamples> wrapper = new MPJLambdaWrapper<ProvideSamples>()
                .selectAll(ProvideSamples.class)
                .leftJoin(Goods.class, Goods::getGoodsId, ProvideSamples::getGoodsId)
                .ne(Goods::getEnterpriseNo, "")
                .isNotNull(Goods::getEnterpriseNo)
                .orderByDesc(ProvideSamples::getCreateTime);

        List<ProvideSamples> list = provideSamplesService.list(wrapper);
        for (ProvideSamples provideSamples : list){
            BehavioralData behavioralData = new BehavioralData();
            behavioralData.setTitle("我刚发布了一个新活动，快来跟我一起组队吧。");// 文案
            behavioralData.setSubject(provideSamples.getSubject());// 标题
            behavioralData.setContent(provideSamples.getSpecification());// 内容（商品/样品规格）
            if(StrUtil.isNotBlank(provideSamples.getGoodsImages())){
                behavioralData.setImage(provideSamples.getGoodsImages().split(",")[0]);// 图片
            }
            behavioralData.setPrice(provideSamples.getSamplePrice().toString());
            behavioralData.setLabel("样品推广价");
            behavioralData.setType("0");// 类型。0动态；1工作；2商品；3创作
            behavioralData.setJumpUrl("/pages_private_scene2/provide_samples/sign_up?docUnid=" + provideSamples.getId());// 样品活动报名页面
            behavioralData.setSourceId(provideSamples.getId());// 来源id
            behavioralData.setSourceType("2");// 来源类型。0团购；1测评；2样品；3招聘；4协作；5上架商品；6发布学习

            behavioralData.setCreateTime(provideSamples.getCreateTime());
            behavioralData.setUpdateTime(provideSamples.getUpdateTime());

            behavioralData.setUserId(provideSamples.getInitiatorId());
            behavioralData.setUserName(provideSamples.getInitiatorName());
            behavioralData.setStatus("1");// 状态。0停用；1启用

            // 获取商品信息
            Goods goods = goodsService.getById(provideSamples.getGoodsId());
            if (BeanUtil.isNotEmpty(goods)){
                behavioralData.setEnterpriseNo(goods.getEnterpriseNo());// 企业编号
                behavioralData.setEnterpriseName(goods.getEnterpriseName());// 企业名称
            }

            if(baseMapper.insert(behavioralData) < 0){
                throw new ServiceException("发布样品行为汇集出错了！");
            }
        }
    }

    /**
     * 2.汇集发布测评数据
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void releaseEvaluation(){

        // 2.发布测评
        HashMap<String, Object> params = new HashMap<>();
        JSONObject resObject = bpmSystemApi.sendHttp(params, "R_meily_BL037");
        if (!"200".equals(resObject.getString("code"))) {
            throw new ServiceException("获取所有测评数据列表失败！");
        }

        String goodsNo = "";
        Goods goods = new Goods();

        // JSONArray 转 list
        String js = JSONObject.toJSONString(resObject.getJSONArray("data"), SerializerFeature.WriteClassName);
        List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);
//        WF_OrUnid as id,Subject as subject, WF_DocCreated as createTime, WF_LastModified as updateTime, Initiatorid as initiatorId, InitiatorName as initiatorName, MainPicture as mainPicture,ProductID as goodsNo, LevelA as levelAReward, LevelB as levelBReward, LevelC as levelCReward
        for (JSONObject object : list){

            String goodsImages = "";// 商品图
            String specification = "";// 商品规格

            if(!goodsNo.equals(object.getString("goodsNo"))){
                LambdaQueryWrapper<Goods> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Goods::getGoodsNo, object.getString("goodsNo"));
                wrapper.ne(Goods::getEnterpriseNo, "");
                wrapper.isNotNull(Goods::getEnterpriseNo);

                goods = goodsService.getOne(wrapper);

                goodsNo = object.getString("goodsNo");
                if(BeanUtil.isNotEmpty(goods)){
                    goodsImages = goods.getGoodsImages();
                    specification = goods.getSpecification();

                    BehavioralData behavioralData = new BehavioralData();
                    behavioralData.setTitle("我刚发布了一个新活动，快来跟我一起组队吧。");// 文案
                    behavioralData.setSubject(object.getString("subject"));// 标题
                    behavioralData.setContent(specification);// 内容（商品/样品规格）

                    // 图片
                    if(StrUtil.isNotBlank(object.getString("mainPicture"))){
                        behavioralData.setImage(object.getString("mainPicture"));
                    } else {
                        if(StrUtil.isNotBlank(goodsImages)){
                            behavioralData.setImage(goodsImages.split(",")[0]);
                        }
                    }

                    // 价格（取A/B/C报酬的最高价）
                    double reward = 0.0;
                    if(StrUtil.isNotBlank(object.getString("LevelA"))){
                        reward = Double.parseDouble(object.getString("LevelA"));
                    }

                    if(StrUtil.isNotBlank(object.getString("LevelB"))){
                        if(Double.parseDouble(object.getString("LevelB")) > reward){
                            reward = Double.parseDouble(object.getString("LevelB"));
                        }
                    }

                    if(StrUtil.isNotBlank(object.getString("LevelC"))){
                        if(Double.parseDouble(object.getString("LevelC")) > reward){
                            reward = Double.parseDouble(object.getString("LevelC"));
                        }
                    }

                    behavioralData.setPrice(String.valueOf(reward));
                    behavioralData.setLabel("品牌推广报酬");
                    behavioralData.setType("0");// 类型。0动态；1工作；2商品；3创作
                    behavioralData.setJumpUrl("/pages_private_scene2/ProductPromote/SignUp?docUnid=" + object.getString("id"));// 跳转测评报名页面
                    behavioralData.setSourceId(object.getString("id"));
                    behavioralData.setSourceType("1");// 来源类型。0团购；1测评；2样品；3招聘；4协作；5上架商品；6发布学习

                    behavioralData.setCreateTime(object.getString("createTime"));
                    behavioralData.setUpdateTime(object.getString("updateTime"));
                    behavioralData.setUserId(object.getString("initiatorId"));
                    behavioralData.setUserName(object.getString("initiatorName"));
                    behavioralData.setEnterpriseNo(goods.getEnterpriseNo());// 企业编号
                    behavioralData.setEnterpriseName(goods.getEnterpriseName());// 企业名称

                    if(baseMapper.insert(behavioralData) < 0){
                        throw new ServiceException("发布测评行为汇集出错了！");
                    }

                }
            }
        }
    }
}
